package com.lala.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lala.config.AlipayConfig;
import com.lala.entity.OrderDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.NOTIFY_URL;
import static com.alipay.api.AlipayConstants.RETURN_URL;

/**
 * @ClassName AliPriceController
 * @Description : 订单支付业务
 *
 * @param
 * @Return :
 * @Author : lixu
 * @Date : 2020/3/29 16:55
*/
@Controller
@RequestMapping("price")

public class AliPriceController {
    @RequestMapping("alipay")
    @ResponseBody
    public void alipay(HttpServletResponse response, HttpServletRequest request,Integer price) throws IOException {
        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = response.getWriter();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest alipayRequest  = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        alipayRequest .setReturnUrl(RETURN_URL);
        alipayRequest .setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =price.toString();
        //订单名称，必填
        String subject ="物流订单";
        alipayRequest .setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest ).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("打桩");
        out.println(form);
    }
    @RequestMapping("notify")
    public void notifyUrl(){
        System.out.println("异步支付成功");

    }
    @RequestMapping("return")
    public void returnUrl(){
        System.out.println("同步支付成功");
    }

}
